﻿using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;

namespace NoMvvm
{
    internal sealed class DynamicCache
    {
        private object _lock = new object();
        private readonly Dictionary<Type, Dictionary<string, CallSite<Func<CallSite, object, object>>>> _dictionary = new Dictionary<Type, Dictionary<string, CallSite<Func<CallSite, object, object>>>>();

        public bool TryGet(Type type, string memberName, out CallSite<Func<CallSite, object, object>> callsite)
        {
            callsite = null;
            Dictionary<string, CallSite<Func<CallSite, object, object>>> members = null;
            lock (_lock)
            {
                return _dictionary.TryGetValue(type, out members) && members.TryGetValue(memberName, out callsite);
            }
        }

        public void Add(Type type, string memberName, CallSite<Func<CallSite, object, object>> callsite)
        {
            Dictionary<string, CallSite<Func<CallSite, object, object>>> members = null;
            lock (_lock)
            {
                if (_dictionary.TryGetValue(type, out members))
                {
                    members[memberName] = callsite;
                }
                else
                {
                    _dictionary[type] = new Dictionary<string, CallSite<Func<CallSite, object, object>>> { { memberName, callsite } };
                }
            }
        }
    }
}
